﻿function ft_IsString(obj) {
    return typeof obj == "string" || obj instanceof String;
}

function autoLogin(username, password) {
    showLoginBox(username, password);
    $(".ft-btn-login-submit").first().trigger("click");
}

function showLoginBox(username, password) {
    $("#tbx-login-user-name").val(username);
    $("#tbx-login-password").val(password);
    $("#cbx-login-remember-password").removeAttr("checked");
    $(".icon-please-wait-login").hide();
    $(".lbl-login-status").html("");
    $("#ft_modal_login").modal();
}

$(function () {
    initializeValidateLoginForm("#form_login");
    function initializeValidateLoginForm(selector) {
        $(selector).bootstrapValidator({
            live: "disabled",
            message: "",
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                requiredField: {
                    selector: selector + ' .validate-required',
                    validators: {
                        notEmpty: { message: "Vui lòng nhập thông tin" },
                    }
                },
            },
        });
    }

    $(".ft-btn-login").click(function () {
        showLoginBox(null, null);
    });

    $('#ft_modal_login').on('shown.bs.modal', function () {
        $("#form_login input:first").focus();
    })

    $(".ft-btn-logout").click(function () {
        $.ajax({
            url: BASE_URL + "Home/Logout",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "JSON",
            data: null,
            success: function (result) {
                $(".ft-btn-logout").hide();
                $(".ft-btn-login").show();
                $(".login-box-myteam-link").html("");
            },
            error: function (xhr, status, err) {
            },
        });
    })

    var __is_login_submitting = false; //when validate form, it automatically raise submit event.
    $("#form_login").submit(function (evt) {
        evt.preventDefault();
        if (!__is_login_submitting)
        {
            __is_login_submitting = true;
            var validFormData = $("#form_login").data('bootstrapValidator');
            validFormData.validate();
            validFormData.setLiveMode('enabled');
            var isValid = validFormData.isValid();
            if (isValid) {
                updateLoginStatus("text-info", "Đang kiểm tra tài khoản...", true);
                var userInfo = {};
                $("#form_login input").each(function () {
                    if ($(this).attr("name") != '' && $(this).val().trim() != '') {
                        if ($(this).attr("type") == "checkbox") userInfo[$(this).attr("name")] = $(this).is(":checked");
                        else userInfo[$(this).attr("name")] = $(this).val().trim();
                    }
                });
                $.ajax({
                    url: BASE_URL + "Home/Login",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "JSON",
                    data: JSON.stringify(userInfo),
                    success: function (result) {
                        if (ft_IsString(result)) {
                            updateLoginStatus("text-danger", "Lỗi: " + result, false);
                            validFormData.updateElementStatus($("#form_login input[type!=checkbox]"), "VALIDATING", null);
                        }
                        else {
                            updateLoginStatus("text-info", "", false);
                            $(".ft-btn-login").hide();
                            $(".ft-btn-logout").show();

                            $(".login-box-myteam-link").html(result.Username);
                            $(".login-box-myteam-link").attr("href", BASE_URL + "Feature/MyTeam/" + result.ID);

                            $("#ft_modal_login").modal("hide");
                        }
                    },
                    error: function (xhr, status, err) {
                        updateLoginStatus("text-danger", "Đăng nhập LỖI, vui lòng thử lại", false);
                    },
                });
            }
            __is_login_submitting = false;
        }
    });

    function updateLoginStatus(textClass, textContent, isShowWaiting) {
        $(".lbl-login-status").attr("class", "lbl-login-status " + textClass);
        $(".lbl-login-status").html(textContent);
        if (isShowWaiting) $(".icon-please-wait-login").show();
        else $(".icon-please-wait-login").hide();
    }
});
